package com.lmaos.basetools.files.scan.parse;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

import com.lmaos.basetools.base.SBaseUtils;
import com.lmaos.basetools.files.scan.ScanFile;
import com.lmaos.basetools.files.scan.ScanFileUtils;
import com.lmaos.basetools.files.scan.SuffixScanFileParse;

public class JarSuffixScanFileParse implements SuffixScanFileParse{

	@Override
	public List<ScanFile> parseScanFiles(String scanRootPath, String filePath, String suffix) {
		List<ScanFile> scanFiles = new ArrayList<ScanFile>();
		FileInputStream in = null;
		try {
			List<JarEntry> jarEntries = getJarEntries(new FileInputStream(ScanFileUtils.getFile(filePath)));
			for (JarEntry jarEntry : jarEntries) {
				String jarEntryPath = jarEntry.getName();
				if(!jarEntry.isDirectory()){
					ScanFile scanFile = new ScanFile(filePath, jarEntryPath, filePath+"!/"+jarEntryPath);
					scanFiles.add(scanFile);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			SBaseUtils.close(in);
		}
		return scanFiles;
	}
	
	public List<JarEntry> getJarEntries(InputStream in){
		JarInputStream jin = null;
		List<JarEntry> jarEntries = new ArrayList<JarEntry>();
		try {
			jin = new JarInputStream(in);
			JarEntry jarEntry = null;
			while((jarEntry = jin.getNextJarEntry())!=null){
				jarEntries.add(jarEntry);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			SBaseUtils.close(jin);
		}
		return jarEntries;
	}
	

}
